package com.ttc.mBackup.BackupAgent;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Environment;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.dropbox.client.DropboxAPI;
import com.dropbox.client.DropboxAPI.Config;
import com.dropbox.client.DropboxAPI.Entry;
import com.ttc.mBackup.BackupActivity;
import com.ttc.mBackup.R;
import com.ttc.mBackup.common.uploaddropbox;

public class LoginAddTask extends Activity {

	/*ProgressDialog*/
	private ProgressDialog _progress;
	
	//Private Performclass
private DropBoxPerform updown;
private ImageView up;
	//private int _TOTask;
	private boolean _WhichTask;
	//Save name of file and Index
private	ArrayList<listviewlocal> model= new ArrayList<listviewlocal>();
	private int _index=0;
	/*Save Dir of ListFile*/
	private String dirfile;
	/*
	 * Create widget to show information and list to do
	 * */
	TextView name,detail;
	ImageView ig;
	ListView lv;
	/*Apdater for listview*/
	private ListLocaltion adapter;
    
	/*Define var for Dropbox
	 * 
	 * */
	private DropboxAPI api = new DropboxAPI();
    private boolean mLoggedIn;
    private Config mConfig;
    private String email;
    private String password;
  //Task to do for Dialog
	int selector=0;
    /**
     * ActionItem for QuickAction Dialog
     * */
	private	final ActionItem _replace = new ActionItem();
	private	final ActionItem _delete= new ActionItem();

	private	final ActionItem _download = new ActionItem();
	private	final ActionItem _restore=new ActionItem();
	private 	QuickAction qa;
   private LoginAsyncTask asyncTask=null;
   
   
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.barlocal);
        
        /*Get last State of Activity*/
      
        SharedPreferences prefs = 
        	getSharedPreferences(LoginDropbox.ACCOUNT_PREFS_NAME, 
        			MODE_WORLD_WRITEABLE);
        email=  prefs.getString(LoginDropbox.ACCOUNT_DROPBOX, "");
        password=prefs.getString(LoginDropbox.PASSWORD_DROPBOX, "");
        showDialog(0);
        getAccountInfo();
        setforActionItem();
          /*List View */
           lv =(ListView) findViewById(R.id.list_local);
           up = (ImageView) findViewById(R.id.image_up);
           up.setVisibility(8);
           /*Receive Data*/
           final Bundle data = getIntent().getExtras();
           if(data!=null)
            {
            			
            _WhichTask = data.getBoolean(BackupActivity.KEY_ACTIVITY);
            AddWidget(_WhichTask,data);
           dirfile=data.getString(BARLocaltion.DIR_CHOICE);		
            }
            		
            		/*Set on Item Click Listenner  for list View*/
            		lv.setOnItemClickListener(new OnItemClickListener()
            		{

            			@Override
            			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
            					long arg3) {
            				// TODO Auto-generated method stub
            				///String[] tmp = (String[]) arg0.getItemAtPosition(arg2);
            				//Toast.makeText(getBaseContext(),model[arg2].getName(), Toast.LENGTH_SHORT).show();
            				_index=arg2;
            				qa = new QuickAction(arg1);
            				if(_WhichTask)
            				{
            					
            					
            					qa.addActionItem(_replace);
            					
            				}
            				else
            				{
            				qa.addActionItem(_restore);	
            				}
            				qa.addActionItem(_download);
            				qa.addActionItem(_delete);
            				qa.setAnimStyle(QuickAction.ANIM_AUTO);
            				
            				qa.show();
            				//CreateDialog(_WhichTask,false,
            					//	data.getCharSequence(BARLocaltion.DIR_CHOICE).toString());
            				
            				
            			}
            			}
            		);
      
       
        
  }
    
    
    




	private ListLocaltion setListCloud() {
    	 
    	model.clear();
    	api=getAPI();
    	 ArrayList<Entry> al = new ArrayList<Entry>();
         al = listDirectory(dirfile,api);
         Iterator<Entry> itr = al.iterator();
         Entry en;
         while (itr.hasNext()) {
        en = itr.next();
         
        model.add(new listviewlocal(en.fileName(),
				R.drawable.androidicon,
				en.modified));
         }
    	adapter = new ListLocaltion(model);
    	
		return adapter;
    	
	}
    public ArrayList<Entry> listDirectory(String path, DropboxAPI api) {
    	
    	DropboxAPI.Entry entry = api.metadata("dropbox", path, 0, null, true);
    	if (!entry.is_dir) return null;
    	return entry.contents;
    	}
    
    
    /**
     * This lets us use the Dropbox API from the LoginAsyncTask
     */
    public DropboxAPI getAPI() {
    	return api;
    }

    /**
     * Convenience function to change UI state based on being logged in
     */
    public void setLoggedIn(boolean loggedIn) {
    	mLoggedIn = loggedIn;
    	
    	if (loggedIn) {
    		lv.setAdapter(setListCloud());
    	
    		
    	} 
    	_progress.dismiss();
    }

    public void showToast(String msg) {
        Toast error = Toast.makeText(this, msg, Toast.LENGTH_LONG);
        error.show();
    }
    
    private void getAccountInfo() {
    	if (api.isAuthenticated()) {
    		// If we're already authenticated, we don't need to get the login info
    		asyncTask = new LoginAsyncTask(this, null, null, getConfig(),true);
    		asyncTask.execute();    		
    	} else {
    	
	        if (email.length() < 5 || email.indexOf("@") < 0 || email.indexOf(".") < 0) {
	            showToast("Error, invalid e-mail");
	            return;
	        }
	        if (password.length() < 6) {
	            showToast("Error, password too short");
	            return;
	        }

	        // It's good to do Dropbox API (and any web API) calls in a separate thread,
	        // so we don't get a force-close due to the UI thread stalling.
	        asyncTask = new LoginAsyncTask(this, email, password, getConfig(),true);
	        asyncTask.execute();
    	}
    }

    
    
    /**
     * This handles authentication if the user's token & secret
     * are stored locally, so we don't have to store user-name & password
     * and re-send every time.
     */
    protected boolean authenticate() {
    	if (mConfig == null) {
    		mConfig = getConfig();
    	}
    	String keys[] = getKeys();
    	if (keys != null) {
	        mConfig = api.authenticateToken(keys[0], keys[1], mConfig);
	        if (mConfig != null) {
	            return true;
	        }
    	}
    	showToast("Failed user authentication for stored login tokens.");
    	setLoggedIn(false);
    	return false;
    }
    
    protected Config getConfig() {
    	if (mConfig == null) {
	    	mConfig = api.getConfig(null, false);
	    	// TODO On a production app which you distribute, your consumer
	    	// key and secret should be obfuscated somehow.
	    	mConfig.consumerKey=LoginDropbox.CONSUMER_KEY;
	    	mConfig.consumerSecret=LoginDropbox.CONSUMER_SECRET;
	    	mConfig.server="api.dropbox.com";
	    	mConfig.contentServer="api-content.dropbox.com";
	    	mConfig.port=80;
    	}
    	return mConfig;
    }
    
    public void setConfig(Config conf) {
    	mConfig = conf;
    }
    
    /**
     * Shows keeping the access keys returned from Trusted Authenticator in a local
     * store, rather than storing user name & password, and re-authenticating each
     * time (which is not to be done, ever).
     * 
     * @return Array of [access_key, access_secret], or null if none stored
     */
    public String[] getKeys() {
        SharedPreferences prefs = getSharedPreferences(LoginDropbox.ACCOUNT_PREFS_NAME, 0);
        String key = prefs.getString(LoginDropbox.ACCESS_KEY_NAME, null);
        String secret = prefs.getString(LoginDropbox.ACCESS_SECRET_NAME, null);
        if (key != null && secret != null) {
        	String[] ret = new String[2];
        	ret[0] = key;
        	ret[1] = secret;
        	return ret;
        } else {
        	return null;
        }
    }
    
    /**
     * Shows keeping the access keys returned from Trusted Authenticator in a local
     * store, rather than storing user name & password, and re-authenticating each
     * time (which is not to be done, ever).
     */
    public void storeKeys(String key, String secret) {
        // Save the access key for later
        SharedPreferences prefs = getSharedPreferences(LoginDropbox.ACCOUNT_PREFS_NAME, MODE_WORLD_WRITEABLE);
        Editor edit = prefs.edit();
        edit.putString(LoginDropbox.ACCESS_KEY_NAME, key);
        edit.putString(LoginDropbox.ACCESS_SECRET_NAME, secret);
        edit.commit();
    }
    
    
    /*Create Input Dialog to put name of backup file
	 *  and call next Activity to choose what you wanna backup */
	private void CreateDialog(boolean whichtask, String dir)
	{
		/*
		 * dirs hold directory to save file
		 * task hold boolean values : Backup- true, Restore - false
		 * one hold boolean values : Create - true or Replace - false
		 * 
		 * Create AlertDialog alert 
		 * Create View EditText and  TextView 
		  */
		
		final String dirs = dir ;
		final boolean task=whichtask;
		
		final AlertDialog.Builder alert = new AlertDialog.Builder(this);
		final EditText input = new EditText(this);
		/*
		 * one hold boolean values : Create - true or Replace - false
		 * check if is Create : put view Edittext into Dialog and settext is 
		 * date in format for it
		 * or not, put TextView and set text for it ... Set some condition if is backup
		 * we replce or restores we overide...
		 * */
		
		
		input.setText(new DateFormat().format("ddMMyyyy", new Date()));
		alert.setView(input);
	
	
		alert.setIcon(R.drawable.erroricon);
		alert.setTitle("Name of Task")
		.setPositiveButton("Continue",
				new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				/*Get name of file*/
				String value = input.getText().toString().trim();
				
				
					Bundle extras = new Bundle();
				/*Send Data and Call BARSelector activity */
				Intent i = new Intent("com.ttc.mBackup.BackupAgent.BARSELECTOR");
				
				extras.putString(BARLocaltion.DIR_CHOICE, dirs);
				extras.putBoolean(BackupActivity.KEY_ACTIVITY, task);
				//Toast.makeText(getBaseContext(), one?value:model[_index].getName(), Toast.LENGTH_SHORT).show();
				extras.putString("FILE_NAME", value);
		
				i.putExtras(extras);
				
				startActivityForResult(i,2);
				
			}
		});
		alert.setNegativeButton("Cancel",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						dialog.cancel();
					}
				});
		alert.show();
	}
	
	/*
	 * AddWidget() method : set text for textview, set value for visibility 
	 * check var hold what type of your task : Backup or Restore
	 * data hold some input data send by previuos activity
	 * */	
		private void AddWidget(boolean check, final Bundle data)
		{
			name = (TextView) findViewById(R.id.title_local);
			detail = (TextView) findViewById(R.id.detail_local);
			ig = (ImageView) findViewById(R.id.image_add);
		
			
			if(check)
			{
			name.setText("BACKUP");
			detail.setText("Create or Replace your task to backup");
			ig.setVisibility(0);
			
			/*Call Dialog Task*/
			ig.setOnClickListener(new View.OnClickListener() {
				
				@Override
				public void onClick(View arg0) {
					// TODO Auto-generated method stub
					
					CreateDialog(true, data.getCharSequence(BARLocaltion.DIR_CHOICE).toString());
				}
			});
			
			}
			else
			{
				name.setText("RESTORE");
				detail.setText("Perform your task to Restore");
			}
			
			
		}
		@Override
		protected void onActivityResult(int requestCode, int resultCode,
				Intent data) {
			// TODO Auto-generated method stub
				if(requestCode==2)
					if(resultCode==2)
					{
						/*if is backup up file in to cloud.... */
						if(data.getBooleanExtra("BACKUP", false)){
						showDialog(0);
						updown = new DropBoxPerform(api,data.getStringExtra("FILE_NAME"));
						updown.uploadfile();
						getAccountInfo();
						
						}
					}
		}
		
		@Override
		protected Dialog onCreateDialog(int id) {
			// TODO Auto-generated method stub
			_progress =  ProgressDialog.show(this, "",
					"Please wait for few seconds...", true);
			_progress.setCancelable(true);
			return _progress;
			
		}
		
	//Download File to Dir	
	private void downloadfile(String value)
	{
		 try {
	            // Make sure the Pictures directory exists.
	            ///File Doc
			 File fis =new File("data/data/com.ttc.mBackup/databases/"+"BACKUPSYSTEM");
	            InputStream is = new FileInputStream(fis);
	            //File ghi
	            OutputStream os = new FileOutputStream( new File(
	            											Environment.getExternalStorageDirectory().getAbsoluteFile()
	            												+File.separator+BackupActivity.DIR_NAME	+File.separator
	            												+value));
	            byte[] data = new byte[is.available()];
	            is.read(data);
	            os.write(data);
	            is.close();
	            os.close();
	            fis.delete();
	            _progress.dismiss();
	            Toast.makeText(getBaseContext(), "Finish You Download ! Please Check You SDcard", Toast.LENGTH_LONG).show();
	            
	        } catch (IOException e) {
	            // Unable to create file, likely because external storage is
	            // not currently mounted.
	            Log.w("ExternalStorage", "Error writing " , e);
	        }
	        
	}
	private void setforActionItem()
	{
		/*Replace ActionItem*/
		_replace.setTitle("Replace");
		_replace.setIcon(getResources().getDrawable(R.drawable.replaceicon));
		_replace.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Bundle extras = new Bundle();
			/*Send Data and Call BARSelector activity */
			Intent i = new Intent("com.ttc.mBackup.BackupAgent.BARSELECTOR");
			
			extras.putString(BARLocaltion.DIR_CHOICE, dirfile);
			extras.putBoolean(BackupActivity.KEY_ACTIVITY, _WhichTask);
			//Toast.makeText(getBaseContext(), one?value:model[_index].getName(), Toast.LENGTH_SHORT).show();
			extras.putString("FILE_NAME", model.get(_index).getName());
	
			i.putExtras(extras);
			qa.dismiss();
			startActivityForResult(i,2);
			}
		});
		
		/*Restore ActionItem*/
		_restore.setTitle("Restore");
		_restore.setIcon(getResources().getDrawable(R.drawable.driveicon));
		_restore.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Bundle extras = new Bundle();
				
				/*
				 *Download  file db in clound 
				 *  
				 * */
				showDialog(0);
				updown = new DropBoxPerform(api,model.get(_index).getName());
				updown.downloadfile(); 
				extras.putBoolean(BARLocaltion.CLOUD_STORE, true);
			
			/*Send Data and Call BARSelector activity */
			Intent i = new Intent("com.ttc.mBackup.BackupAgent.BARSELECTOR");
			
			extras.putString(BARLocaltion.DIR_CHOICE, dirfile);
			extras.putBoolean(BackupActivity.KEY_ACTIVITY, _WhichTask);
			
			//Toast.makeText(getBaseContext(), one?value:model[_index].getName(), Toast.LENGTH_SHORT).show();
			extras.putString("FILE_NAME", model.get(_index).getName());
	
			i.putExtras(extras);
			qa.dismiss();
			_progress.dismiss();
			startActivityForResult(i,2);
			}
		});
		
		/*Upload ActionItem*/
		_download.setTitle("Download");
		_download.setIcon(getResources().getDrawable(R.drawable.downloadicon));
		_download.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				/*
				 * Download file from Dropbox
				 * */
				showDialog(0);
				updown = new DropBoxPerform(api,model.get(_index).getName());
				updown.downloadfile(); 
				downloadfile( model.get(_index).getName());
				qa.dismiss();
			}
		});
		
		/*Delete*/
		_delete.setTitle("Delete");
		_delete.setIcon(getResources().getDrawable(R.drawable.deleteicon));
		_delete.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				while(true)
				{
					if(api.delete("dropbox","/BackupSystems"+File.separator+model.get(_index).getName()))
					{
						
						
						
						model.remove(_index);
						adapter.notifyDataSetChanged();
						Toast.makeText(getBaseContext(),"Delete Successfull ... " , Toast.LENGTH_LONG).show();
						break;
					}
				}
				qa.dismiss();
			}
		});
	}
	
}
